package com.dingding.transfer.stamper.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingding.transfer.stamper.dao.CompInfoDao;
import com.dingding.transfer.stamper.dao.DeptDao;
import com.dingding.transfer.stamper.dao.UserDao;
import com.dingding.transfer.stamper.dao.UserDeptDao;
import com.dingding.transfer.stamper.dto.DeptInfo;
import com.dingding.transfer.stamper.dto.UserInfo;
import com.dingding.transfer.stamper.entity.CompInfo;
import com.dingding.transfer.stamper.entity.Dept;
import com.dingding.transfer.stamper.entity.User;
import com.dingding.transfer.stamper.entity.UserDept;
import com.dingding.transfer.stamper.service.DingDingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/3/31 15:59
 **/
@Component
@Slf4j
public class ContextRefreshedListener {
    @Autowired
    private DeptDao deptDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CompInfoDao compInfoDao;

    @Autowired
    private UserDeptDao userDeptDao;

    @Autowired
    private DingDingService dingDingService;


    @EventListener(classes={ApplicationEvent.class}) //classes 监听器的类型
    public void listen(ApplicationEvent event){
        if(event instanceof ContextRefreshedEvent){
            log.info("员工部门信息初始化+++++++++++++++++++++++++");
            try {
                List<CompInfo> list = compInfoDao.selectList(new QueryWrapper<CompInfo>().eq("status", true));
                if(CollectionUtil.isNotEmpty(list)){
                    for (CompInfo compInfo :
                            list) {
                        // 如果不传，默认部门为根部门，根部门ID为1
                        List<DeptInfo> deptInfos = getDeptInfos("1",compInfo);
                        Set<DeptInfo> set = new HashSet<>();
                        set.addAll(deptInfos);
                        for (DeptInfo deptInfo :
                                set) {
                            // 获取所有员工
                            getUserInfos(deptInfo.getDeptId().toString(),compInfo);
                        }
                    }
                }

            } catch (Exception e) {
                log.error("员工部门信息初始化失败{}",e.getMessage());
            }
        }
    }

    public void addDeptInfo(String corpId,String deptId){
        CompInfo compInfo = compInfoDao.selectOne(new QueryWrapper<CompInfo>().eq("corp_id", corpId));
        List<DeptInfo> deptInfos = getDeptInfos(deptId, compInfo);
        Set<DeptInfo> set = new HashSet<>();
        set.addAll(deptInfos);
        for (DeptInfo deptInfo :
                set) {
            // 获取所有员工
            getUserInfos(deptInfo.getDeptId().toString(),compInfo);
        }
    }

    public void deleteDept(String corpId,String deptId){
        CompInfo compInfo = compInfoDao.selectOne(new QueryWrapper<CompInfo>().eq("corp_id", corpId));
        List<DeptInfo> deptInfos = delteDeptInfos(deptId, compInfo);
        Set<DeptInfo> set = new HashSet<>();
        set.addAll(deptInfos);
        for (DeptInfo deptInfo :
                set) {
            // 删除部门员工对应关系
            deleteUserInfos(deptInfo.getDeptId().toString());
        }
    }

    private List<DeptInfo> delteDeptInfos(String deptId, CompInfo compInfo) {
        List<DeptInfo> deptInfos = dingDingService.getDeptInfo(compInfo,deptId);
        if(CollectionUtil.isNotEmpty(deptInfos)){
            List<DeptInfo> copyDeptInfos = new ArrayList<>(deptInfos);
            log.info("部门信息初始化");
            deptInfos.forEach(deptInfo -> {
                try {
                    deptDao.delete(new QueryWrapper<Dept>().eq("dept_id",deptInfo.getDeptId()));
                } catch (Exception e) {
                    log.error("部门信息为{},删除出错{},",deptInfo.toString(),e.getMessage());
                }
                copyDeptInfos.addAll(delteDeptInfos(deptInfo.getDeptId().toString(),compInfo));
            });
            return copyDeptInfos ;
        }else {
            return new ArrayList<>();
        }
    }

    public List<DeptInfo> getDeptInfos(String deptId,CompInfo compInfo){
        List<DeptInfo> deptInfos = dingDingService.getDeptInfo(compInfo,deptId);
        if(CollectionUtil.isNotEmpty(deptInfos)){
            List<DeptInfo> copyDeptInfos = new ArrayList<>(deptInfos);
            log.info("部门信息初始化");
            deptInfos.forEach(deptInfo -> {
                try {
                    Dept dept = new Dept();
                    if(deptDao.selectOne(new QueryWrapper<Dept>().eq("dept_id",deptInfo.getDeptId())) == null){
                        BeanUtil.copyProperties(deptInfo,dept);
                        dept.setCompId(compInfo.getCompId());
                        deptDao.insert(dept);
                    }
                } catch (Exception e) {
                    log.error("部门信息为{},插入出错{},",deptInfo.toString(),e.getMessage());
                }
                copyDeptInfos.addAll(getDeptInfos(deptInfo.getDeptId().toString(),compInfo));
            });
            return copyDeptInfos ;
        }else {
            return new ArrayList<>();
        }
    }

    public void addUser(String corpId,String userId){
        UserInfo userInfo = dingDingService.getUserInfo(corpId, userId);
        CompInfo compInfo = compInfoDao.selectOne(new QueryWrapper<CompInfo>().eq("corp_id", corpId));
        addUserContent(userInfo,compInfo.getCompId());
    }


    private void deleteUserInfos(String deptId) {
        try {
            userDeptDao.delete(new QueryWrapper<UserDept>().eq("dept_id",deptId));
        } catch (Exception e) {
            log.error("删除部门员工对应关系出错{}",e);
        }
    }

    public void getUserInfos(String deptId,CompInfo compInfo){
        log.info("员工信息初始化");
        List<UserInfo> userInfos = dingDingService.getUserInfo(compInfo,deptId);
        if(CollectionUtil.isNotEmpty(userInfos)){
            userInfos.forEach(userInfo -> {
                addUserContent(userInfo,compInfo.getCompId());
            });
        }
    }

    /**
     * 添加用户相关信息
     * @param userInfo
     */
    private void addUserContent(UserInfo userInfo,int compId){
        try {
            User user = new User();
            if(userDao.selectOne(new QueryWrapper<User>().eq("userid",userInfo.getUserid())) == null){
                BeanUtil.copyProperties(userInfo,user);
                user.setCompId(compId);
                userDao.insert(user);
                List<String> deptIdList = userInfo.getDeptIdList();
                if(CollectionUtil.isNotEmpty(deptIdList)){
                    deptIdList.forEach(a ->{
                        UserDept userDeptInfo = userDeptDao.selectOne(new QueryWrapper<UserDept>().eq("user_id", user.getUserid())
                                .eq("dept_id", a));
                        if(userDeptInfo == null){
                            UserDept userDept = new UserDept();
                            userDept.setUserId(user.getUserid());
                            userDept.setDeptId(a);
                            userDeptDao.insert(userDept);
                        }
                    });
                }
            }
        } catch (Exception e) {
            log.error("用户信息为{},插入出错{}",userInfo.toString(),e.getMessage());
        }
    }
}
